package com.zy.dp.composite.example5;

import java.util.ArrayList;
import java.util.List;

public class Composite extends Component
{
	private List<Component> childComponents = null;
	private String name = "";

	public Composite(String name)
	{

		this.name = name;
	}

	public void addChild(Component child)
	{

		if (childComponents == null)
		{
			childComponents = new ArrayList<Component>();
		}

		childComponents.add(child);
		child.setParent(this);

	}

	public void removeChild(Component child)
	{

		if (childComponents != null)
		{

			int index = childComponents.indexOf(child);
			if (index != -1)
			{

				for (Component c : child.getChildren())

				{
					c.setParent(this);

					childComponents.add(c);

				}

				childComponents.remove(index);

			}

		}

	}

	public List<Component> getChildren()
	{

		return childComponents;

	}

	@Override
	public void printStruct(String preStr)
	{
		System.out.println(preStr + "-" + this.name);

		if (this.childComponents != null)
		{
			preStr += " ";
			for (Component c : childComponents)
			{
				c.printStruct(preStr);
			}
		}

	}

}
